# -*- coding: utf-8 -*-
# @Time    : 2016/9/20

import re
from sympy import expand, simplify
from mathsolver.functions.base.base import BaseFunction, new_latex
from mathsolver.functions.base.objects import BasePoly


class HanShuBianHuaLiang(BaseFunction):
    """函数的变化量"""

    def solver(self, *args):
        fun, start, end = args[0], args[1].sympify(), args[2].sympify()
        x, y, expression = fun.var, fun.name, fun.expression
        start_value, end_value = simplify(expression.subs(x, start)), simplify(expression.subs(x, end))
        result = expand(end_value - start_value)

        # 把 \Delta{\left (x \right )} 替换成 \Delta x
        p = re.compile(r"\\Delta\{\\left \((.*?) \\right \)\}")
        end_print = p.sub(r"\Delta \1", new_latex(end))
        end_value_print = p.sub(r"\Delta \1", new_latex(end_value))
        result_print = p.sub(r"\Delta \1", new_latex(result))

        self.steps.append(["当 {} = {} 时 {} = {}".format(new_latex(x), new_latex(start), new_latex(y), new_latex(start_value)),
                           "当 {} = {} 时 {} = {}".format(new_latex(x), end_print, new_latex(y), end_value_print)])

        self.steps.append(["将两式相减得 \\Delta {} = {}".format(new_latex(y), result_print), ])

        self.output.append(BasePoly(result))
        self.label.add("函数的变化量")

        return self


if __name__ == "__main__":
    pass
